package com.demo.common.job;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.demo.common.model.Flightno;
import com.demo.common.model.Proxyip;
import com.demo.webmagic.pageProcessor.PageProcessorVeryZhunFlighInfo;
import com.demo.webmagic.pipeline.PipelineVeryZhunFlightInfo;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Record;

import us.codecraft.webmagic.Spider;

public class JobFlightInfo implements Job {

	private static final Log log = Log.getLog(JobFlightInfo.class);
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {

		String[] urlStrs = null;

		//是否需要判断航班状态
		if(Flightno.dao.isNeedToJudgeStatus()) {
			List<Record> recordList = Flightno.dao.findLastestStatus();
			Set<String> fnoSet = new HashSet<String>();
			for (Record record : recordList) {
				if(!"已经到达".equals(record.get("flightStatus")) && !"已经取消".equals(record.get("flightStatus"))) {
					fnoSet.add(record.getStr("fno"));
				}
			}
			urlStrs = new String[fnoSet.size()];
			int i = 0;
			for (String fno : fnoSet) {
				urlStrs[i++] = "http://www.veryzhun.com/searchnum.asp?flightnum=" + fno;
			}
		} else {
			List<Flightno> flightList = Flightno.dao.find("SELECT * FROM flightno");
			urlStrs = new String[flightList.size()];
			for (int i = 0; i < flightList.size(); i++) {
				urlStrs[i] = "http://www.veryzhun.com/searchnum.asp?flightnum=" + flightList.get(i).getFno();
			}
		}

		// 查找代理
		List<Proxyip> proxyIpList = Proxyip.dao.find("SELECT * FROM proxyip WHERE isVali = 1 GROUP BY ipStr");

		if(urlStrs != null) {
			Spider.create(new PageProcessorVeryZhunFlighInfo(proxyIpList)).addUrl(urlStrs).addPipeline(new PipelineVeryZhunFlightInfo()).thread(20).start();
		} else {
			log.error("获取url地址出错，同步任务结束");
		}
		//int num = urlStrs.length / proxyIpList.size();
		
		/*if (num > 0) {
			for (int i = 0; i < proxyIpList.size(); i++) {
				Proxyip proxyip = proxyIpList.get(i);
				String[] _urlStrs;
				if (i != proxyIpList.size() - 1) {
					_urlStrs = new String[num];
				} else {
					_urlStrs = new String[urlStrs.length - num * (proxyIpList.size() - 1)];
				}
				for (int j = 0; j < _urlStrs.length; j++) {
					_urlStrs[j] = "http://www.veryzhun.com/searchnum.asp?flightnum="
							+ flightList.get(i * num + j).getFno();
				}
				Spider.create(new PageProcessorVeryZhunFlighInfo(proxyip)).addUrl(_urlStrs)
						.addPipeline(new PipelineVeryZhunFlightInfo()).start();
			}
		} else {
			for (int i = 0; i < urlStrs.length; i++) {
				Spider.create(new PageProcessorVeryZhunFlighInfo(proxyIpList.get(i))).addUrl(urlStrs[i])
						.addPipeline(new PipelineVeryZhunFlightInfo()).start();
			}
		}*/
	}

}
